//
//  GameManager.m
//  gong
//
//  Created by echo on 14-1-11.
//  Copyright (c) 2014年 echo. All rights reserved.
//

#import "GameManager.h"
#import "Constants.h"
#import "SimpleAudioEngine.h"
#import "UICreator.h"
#import "PositionTools.h"
#import "BlockAlertView.h"
#import "TaskManager.h"

@implementation GameManager
{
    CAEmitterLayer *_mortor;
    NSMutableArray *_memoryArray;
}

SharedInstanceBuilder(GameManager)

- (id)init
{
    self = [super init];
    if (self) {
        _mortor = [CAEmitterLayer layer];
        self.memory = [[Memory alloc] init];
        self.memory.houseName = @"大街";
    }
    return self;
}

- (UIView*)createEntryView
{
    return nil;
}

- (UIView*)createMainGameView
{
    return nil;
}

- (void)gotoStreet
{
    NSLog(@"你来到了大街上");
    self.memory.isInStreet = YES;
    self.memory.house = @"";
    [GameManager sharedInstance].currentPlaceName = @"大街";
    [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"Butterfly Dance.mp3" loop:YES];
}

- (void)gotoPlace
{
    
}

- (void)showAward:(NSString*)awardText
{
    [self addParticlesWithPoint:CGPointMake(100, 100) toView:self.gameMainViewContainer];
    
    UILabel *label = [UICreator createLabel:awardText constrainedSize:CGSizeMake(300, CGFLOAT_MAX) color:[UIColor blueColor] font:[UIFont systemFontOfSize:26]];
    label.backgroundColor = [UIColor whiteColor];
    
    UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width + 60, label.frame.size.height)];
    [PositionTools placeView:label atTheLeftMiddleOfTheView:baseView offset:0];
    
    UIButton *closeButton = [UICreator createButtonWithNormalImage:@"redcloseButton.png" highlightedImage:nil target:self action:@selector(closeAward)];
    [PositionTools placeView:closeButton atTheRightMiddleOfTheView:baseView offset:0];
    
    baseView.tag = AwardTag;
    
    [PositionTools placeView:baseView atTheLeftBottomOfTheView:self.gameMainViewContainer offset:CGSizeMake(20, 20)];
    label.alpha = 0;
    
    [UIView animateWithDuration:.5 animations:^{
        label.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)closeAward
{
    [self removeParticleEffect];
    UIView *awardView = [self.gameMainViewContainer viewWithTag:AwardTag];
    [awardView removeFromSuperview];
}

- (void)beginShowRandomNpcInStreet
{
    
}

- (void)removeParticleEffect
{
    [_mortor removeFromSuperlayer];
}

- (void)addParticlesWithPoint:(CGPoint)point toView:(UIView*)container
{
    [container.layer addSublayer:_mortor];
    
    CGPoint originalPoint = CGPointMake(CGRectGetMaxX(container.bounds),
                                        CGRectGetMaxY(container.bounds));
    
    CGPoint newOriginPoint = CGPointMake(originalPoint.x - originalPoint.x/2,
                                         originalPoint.y - originalPoint.y/2);
    
    CGPoint position = CGPointMake(newOriginPoint.x + point.x,
                                   newOriginPoint.y + point.y);
    
    UIImage *image = [UIImage imageNamed:@"tspark.png"];
    
	
	_mortor.emitterPosition = position;
	_mortor.renderMode = kCAEmitterLayerBackToFront;
	
	//Invisible particle representing the rocket before the explosion
	CAEmitterCell *rocket = [CAEmitterCell emitterCell];
	rocket.emissionLongitude = M_PI / 2;
	rocket.emissionLatitude = 0;
	rocket.lifetime = 1.6;
	rocket.birthRate = 1;
	rocket.velocity = 40;
	rocket.velocityRange = 100;
	rocket.yAcceleration = -250;
	rocket.emissionRange = M_PI / 4;
	rocket.color = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5].CGColor;
	rocket.redRange = 0.5;
	rocket.greenRange = 0.5;
	rocket.blueRange = 0.5;
	
	//Name the cell so that it can be animated later using keypath
	[rocket setName:@"rocket"];
	
	//Flare particles emitted from the rocket as it flys
	CAEmitterCell *flare = [CAEmitterCell emitterCell];
	flare.contents = (id)image.CGImage;
	flare.emissionLongitude = (4 * M_PI) / 2;
	flare.scale = 0.4;
	flare.velocity = 100;
	flare.birthRate = 45;
	flare.lifetime = 1.5;
	flare.yAcceleration = -350;
	flare.emissionRange = M_PI / 7;
	flare.alphaSpeed = -0.7;
	flare.scaleSpeed = -0.1;
	flare.scaleRange = 0.1;
	flare.beginTime = 0.01;
	flare.duration = 0.7;
	
	//The particles that make up the explosion
	CAEmitterCell *firework = [CAEmitterCell emitterCell];
	firework.contents = (id)image.CGImage;
	firework.birthRate = 9999;
	firework.scale = 0.6;
	firework.velocity = 130;
	firework.lifetime = 2;
	firework.alphaSpeed = -0.2;
	firework.yAcceleration = -80;
	firework.beginTime = 1.5;
	firework.duration = 0.1;
	firework.emissionRange = 2 * M_PI;
	firework.scaleSpeed = -0.1;
	firework.spin = 2;
	
	//Name the cell so that it can be animated later using keypath
	[firework setName:@"firework"];
	
	//preSpark is an invisible particle used to later emit the spark
	CAEmitterCell *preSpark = [CAEmitterCell emitterCell];
	preSpark.birthRate = 80;
	preSpark.velocity = firework.velocity * 0.70;
	preSpark.lifetime = 1.7;
	preSpark.yAcceleration = firework.yAcceleration * 0.85;
	preSpark.beginTime = firework.beginTime - 0.2;
	preSpark.emissionRange = firework.emissionRange;
	preSpark.greenSpeed = 100;
	preSpark.blueSpeed = 100;
	preSpark.redSpeed = 100;
	
	//Name the cell so that it can be animated later using keypath
	[preSpark setName:@"preSpark"];
	
	//The 'sparkle' at the end of a firework
	CAEmitterCell *spark = [CAEmitterCell emitterCell];
	spark.contents = (id)image.CGImage;
	spark.lifetime = 0.05;
	spark.yAcceleration = -250;
	spark.beginTime = 0.8;
	spark.scale = 0.4;
	spark.birthRate = 10;
	
	preSpark.emitterCells = [NSArray arrayWithObjects:spark, nil];
	rocket.emitterCells = [NSArray arrayWithObjects:flare, firework, preSpark, nil];
	_mortor.emitterCells = [NSArray arrayWithObjects:rocket, nil];
	
    //Force the view to update
	[container setNeedsDisplay];
}

- (void)save
{
    NSLog(@"save memory");
    
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"请选择" message:@""];
    for (int i=0; i<MemoryCount; i++) {
        NSString *title = [NSString stringWithFormat:@"保存当前进度在记忆%i    ", i+1];
        [alert addButtonWithTitle:title block:^{
            [self saveTo:i];
        }];
    }
    
    [alert show];
}

- (void)saveTo:(NSInteger)memoryIndex
{
    NSLog(@"save to memory %i", memoryIndex);
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    self.memory.saveTime = currentDateStr;
    
    NSInteger saveIndex = memoryIndex + 1;
    self.memory.saveIndex = saveIndex;
    
    NSString *fullPath = [self getMemoryFilePath:saveIndex];
    [NSKeyedArchiver archiveRootObject:self.memory toFile:fullPath];
}

- (void)loadMemory
{
    if (_memoryArray) {
        [_memoryArray removeAllObjects];
    }
    _memoryArray = [NSMutableArray array];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *infoFolder = [self getDocumentDirectoryPath];
    NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:infoFolder];
    
    NSString *filename;
    while (filename = [direnum nextObject]) {
        if ([[filename pathExtension] isEqualToString:MemorySuffix]) {
            NSString *fullpath = [NSString stringWithFormat:@"%@/%@", [self getDocumentDirectoryPath], filename];
            Memory *info = (Memory*)[NSKeyedUnarchiver unarchiveObjectWithFile:fullpath];
            if (info) {
                [_memoryArray addObject:info];
            }
        }
    }
}

- (BOOL)hasMemory
{
    return _memoryArray.count > 0;
}

- (NSString*)getMemoryFilePath:(NSInteger)saveIndex
{
    NSString *fullPath = [NSString stringWithFormat:@"%@/memory-%i.%@", [self getDocumentDirectoryPath], saveIndex, MemorySuffix];
    return fullPath;
}

- (void)loadMemoryByIndex:(NSInteger)saveIndex
{
    self.memory = _memoryArray[saveIndex];
}

- (NSString *)getDocumentDirectoryPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    return documentDirectory;
}

@end
